#coding=utf8 
import os;
import time;
import json;
import util;
import mail;
import time_util;
import sys;
def getCharset():
    import platform;
    return platform.system()=='Windows' and "gbk" or "utf8";
    
def getStr(str):
    charset = getCharset();
    if charset=='gbk':
            str = unicode(str,charset)
    return str;

def sendMail(hasSeatCount,imgData,bookUrl="#",dateStr='周六'):
    title = u'临空羽毛球预订提醒:%s的球场还有%s个场地未预订'%(dateStr,hasSeatCount);
    if bookUrl.find('http')!=0 or bookUrl.find('www')!=0:
        bookUrl = 'http://www.gewara.com'+bookUrl;
    html = u'''<p>预订地址：<a href="%s" target="_blank">猛戳</a></p>
<script>console.log(1);</script>
<div>
    <p>以下是当前预订情况网页截图：
        <span style="color:#888;font-size:90%%">(QQ邮箱不可见)</span>
    </p>
    <img src="data:image/png;base64,%s"/>
</div>'''%(bookUrl,imgData);
#    writeFile(html, "d:/mail.html");
    mailto_list=["1698099@qq.com","yangziyexing@qq.com",'shixiaobao17145@163.com','466917670@qq.com']
    return mail.send_mail(mailto_list,title,html)

def runSpy(cfg,dateStr="周六"):
    # defaultDir = "/home/bob/js/"; 
    defaultDir = "%s/js/"%(currentDir); 
    #defaultDir = "D:\\SynchFolder\\casperScripts\\"; 
    cmd = "casperjs "+defaultDir+"linkong.js "+dateStr;
    print cmd;
    rtn = util.cmd2(cmd);
    out = rtn.stdout.readlines();
    error =  rtn.stderr.readlines();
    error_str = None if error is None else ''.join(error)
    rslt_str = None if out is None else ''.join(out)
    print "error:"+getStr(error_str)
    #print "result:"+getStr(rslt_str)
    result_obj ={'result':True} if rslt_str is None or rslt_str.strip()=='' else {'result':False} if rslt_str.find('timeout')>-1 else  json.loads(getStr(rslt_str));
    isOk = False
    if error_str=='' and result_obj['result'] is True:
        imgData = result_obj['imgData'];
        bookUrl = result_obj['bookUrl'];
        hasSeatCount = result_obj['hasSeatCount'];
        if cfg is None:
            lastSend_hasSeatCount = None
            lastSend_time = None;
        else:
            lastSend_hasSeatCount = cfg['lastSend_hasSeatCount'] if 'lastSend_hasSeatCount' in cfg else None;
            lastSend_time = cfg['lastSend_time'] if 'lastSend_time' in cfg else None;
            last_dateStr = cfg['last_dateStr'] if 'last_dateStr' in cfg else "";
        isToSend = True;#是否发送邮件提醒
        maxHasSeat = 80 #total:104
        maxTimeDiffToSend = 10*60 #1小时
        if lastSend_hasSeatCount is not None and lastSend_time is not None and last_dateStr == dateStr.decode(getCharset()):
            timeDiff = time_util.dateMinDate(time_util.Time2ISOString(time.time()),lastSend_time)
            if (lastSend_hasSeatCount==hasSeatCount and timeDiff<23*3600) or hasSeatCount>maxHasSeat:
                log = u"检查到不符合发送邮件条件：hasSeatCount=%s没有发生变化，或者hasSeatCount=%s大于发送邮件剩余座位下限数%s"%(hasSeatCount,hasSeatCount,maxHasSeat);
                writeLog(log,logFile)
                isToSend = False
            else:
                if timeDiff<maxTimeDiffToSend:
                    log = u"检查到不符合发送邮件条件：距离上次发送时间%s差%s秒，小于最小发送间隔时长%s分钟"%(lastSend_time,timeDiff,maxTimeDiffToSend/60);
                    #print log
                    writeLog(log,logFile)
                    isToSend = False
        if isToSend:
            log = u"准备发送邮件了....";
            writeLog(log,logFile)
            mail_dateStr = result_obj['dateStr'] if 'dateStr' in result_obj else dateStr
            send_mail_result = sendMail(hasSeatCount,imgData,bookUrl,mail_dateStr);
            if send_mail_result:
                log = u"发送邮件成功，准备写日志文件:lastSend_hasSeatCount:%s，lastSend_time：%s"%(hasSeatCount,time_util.getCurrentTime());
                writeLog(log,logFile)
                cfg = {} if cfg is None else cfg;
                cfg['lastSend_hasSeatCount'] = hasSeatCount;
                cfg['lastSend_time'] = time_util.Time2ISOString(time.time());
                cfg['last_dateStr'] = getStr(dateStr);
                writeCfg(cfg,cfg_filepath);
                print "发送成功"
            else:  
                writeLog(u"发送邮件失败",logFile)
                print "发送失败"
        else:
            writeLog(u"发送邮件的条件不符合，不发送邮件",logFile)
        isOk = True;
    return {'isOk':isOk,'error':error_str,'rslt_str':rslt_str};

def writeCfg(content,filename='config_linkong.txt',mode='w'):
        content = json.dumps(content);
        writeFile(content, filename, mode);
        
def writeFile(content,filename,mode='w'):
    f = open(filename,mode);
    content = content;
    f.write(content);
    f.close();
def writeLog(content,filename,mode='a'):
    content = "%s%s"%(content,'\n');
    content = content.encode('utf8');
    writeFile(content,filename,mode)

def readCfg(filename='config_linkong.txt'):
    if os.path.exists(filename) is False:
        return None;
    f = open(filename,'r');
    content = f.read();
    content = json.loads(content); 
    f.close();
    return content;

currentDir = os.path.split(os.path.realpath(__file__))[0];
cfg_filepath = '%s/config_linkong.txt'%(currentDir);
cfg = readCfg(cfg_filepath);

import time;
currentTime = time_util.getCurrentTime()
logFile = "%s/log_notify_linkong.txt"%(currentDir);
print currentTime+":begin run....";
writeLog(currentTime+":begin run....",logFile)
dateStr = sys.argv[1] if len(sys.argv)>1 else '周一'
isOk = runSpy(cfg,dateStr)
if isOk['isOk'] is False:
    log = "%s:pub error!error=>%s,rslt_str:%s"%(currentTime,isOk['error'],isOk['rslt_str']);
    writeLog(log.decode(getCharset()), logFile, "a")
